package ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Main
{
	public static void main(String[] args)
	{
		String hostname = "10.61.1.1";
		String username = "root";
		String password = "admin";
		
		
		if(args.length!=0){
			IpAddress ip = new IpAddress(args[0]);
		try
		{
			Connection conn = new Connection(hostname);
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);

			if (isAuthenticated == false)
				throw new IOException("autenticacao falha");
			else{ 
				System.out.println("autenticado com sucesso!");
				/* Create a session */

				Session sess = conn.openSession();

				System.out.println("executando bloqueio!!");
				sess.execCommand("iptables -I USR_FORWARD 1 -p tcp -i eth0 -s "+ip.getIp()+"/24 -d 0.0.0.0/0 --sport 1:65000 --dport 80 -j DROP ");
				//sess.execCommand("iptables -A USR_INPUT -p icmp --icmp-type 8 -s 0/0 -d 192.168.109.30/24 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT");
				InputStream result = sess.getStdout();
				System.out.println(result);


				InputStream stdout = new StreamGobbler(sess.getStdout());

				BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

				while (true){
					String line = br.readLine();
					if (line == null)
						break;
					System.out.println(line);
				}
				System.out.println("ExitCode: " + sess.getExitStatus());

				/* Close this session */

				sess.close();
				conn.close();
			}

		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
	}
	}
}
